package cn.harry.modular.sms.service.impl;

import cn.harry.modular.sms.config.property.AliyunSmsProperties;
import cn.harry.modular.sms.param.SmsParam;
import cn.harry.modular.sms.service.SmsStrategy;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * 阿里大鱼短信发送策略
 *
 * @author harry
 * @公众号 Harry技术
 */

@Slf4j
@Component
@ConditionalOnProperty(value = "sms.aliyun.enable", havingValue = "true")
@RequiredArgsConstructor
public class AliDaYuSmsStrategy implements SmsStrategy {

    /**
     * 产品名称:云通信短信API产品,开发者无需替换
     */
    private static final String PRODUCT = "Dysmsapi";

    /**
     * 产品域名,开发者无需替换
     */
    private static final String DOMAIN = "dysmsapi.aliyuncs.com";

    private final AliyunSmsProperties aliyunSmsProperties;

    @Override
    public SendSmsResponse send(SmsParam sendSmsParam) {
        try {
            return sendSms(sendSmsParam);
        } catch (ClientException e) {
            log.error("发送短信失败", e);
        }
        return BeanUtil.copyProperties(JSONUtil.parseObj("{\"message\":\"短信模块发送发送短信异常 请查看日志\"}"), SendSmsResponse.class);
    }

    private SendSmsResponse sendSms(SmsParam sendSmsParam) throws ClientException {

        String templateCode = sendSmsParam.getTemplateCode();
        // 可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        // 初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile(aliyunSmsProperties.getRegionId(), aliyunSmsProperties.getAccessKeyId(), aliyunSmsProperties.getAccessKeySecret());
        DefaultProfile.addEndpoint(aliyunSmsProperties.getRegionId(), PRODUCT, DOMAIN);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        String mobileList = String.join(",", sendSmsParam.getMobileList());
        String templateParam = JSONUtil.toJsonStr(sendSmsParam.getParams());

        // 组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        // 必填:待发送手机号
        request.setPhoneNumbers(mobileList);
        // 必填:短信签名-可在短信控制台中找到
        request.setSignName(aliyunSmsProperties.getSignName());
        // 必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);

        request.setTemplateParam(templateParam);

        // hint 此处可能会抛出异常，注意catch
        return acsClient.getAcsResponse(request);
    }
}
